import { useState, useEffect } from 'react';
import {
    Card, Text, Group, Stack, TextInput, Button, Table, ActionIcon, Modal,
    Select, PasswordInput, Pagination, Badge, Loader, ScrollArea, Avatar, Center
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import { Dropzone, FileWithPath } from '@mantine/dropzone';
import axios from 'axios';
import { IconSearch, IconEdit, IconTrash, IconEye, IconUserCircle, IconSettings, IconPlus, IconUpload, IconPhoto, IconX } from '@tabler/icons-react';

// 日期格式化函数
const formatDate = (dateString: string): string => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString;

    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }).replace(/\//g, '-');
};

interface User {
    id: number;
    username: string;
    email: string;
    password?: string;
    role: string;
    createdAt: string;
    status: 'active' | 'inactive';
    avatar?: string;
}

const Users = () => {
    const [users, setUsers] = useState<User[]>([]);
    const [loading, setLoading] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const [activePage, setActivePage] = useState(1);
    const [totalPages, setTotalPages] = useState(1);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);
    const [detailsOpened, setDetailsOpened] = useState(false);
    const [editOpened, setEditOpened] = useState(false);
    const [deleteOpened, setDeleteOpened] = useState(false);

    const [avatarFile, setAvatarFile] = useState<FileWithPath | null>(null);
    const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
    const [avatarUploading, setAvatarUploading] = useState(false);

    const form = useForm({
        initialValues: {
            username: '',
            email: '',
            role: 'user',
            password: '',
            status: 'active' as 'active' | 'inactive',
            avatar: ''
        },
        validate: {
            username: (value) => (value.length < 3 ? '用户名至少3个字符' : null),
            email: (value) => (/^\S+@\S+$/.test(value) ? null : '无效的邮箱格式'),
            password: (value) => (editOpened && value !== '' && value.length < 6 ? '密码至少6个字符' : null),
        },
    });

    // 获取用户列表
    const fetchUsers = async (page = activePage) => {
        setLoading(true);
        try {
            const response = await axios.get('/app-api/users', {
                params: {
                    page,
                    per_page: 5,
                    search: searchTerm
                }
            });

            if (response.data) {
                setUsers(response.data.users || []);
                setTotalPages(response.data.pagination?.pages || 1);
            }
        } catch (error) {
            console.error('Failed to fetch users:', error);
            notifications.show({
                title: '获取用户列表失败',
                message: error instanceof Error ? error.message : '请稍后再试',
                color: 'red',
            });
        } finally {
            setLoading(false);
        }
    };

    // 初始加载和搜索时获取用户
    useEffect(() => {
        fetchUsers();
    }, [searchTerm]);

    // 打开用户详情
    const openUserDetails = (user: User) => {
        setSelectedUser(user);
        setDetailsOpened(true);
    };

    // 打开编辑用户
    const openEditUser = (user: User) => {
        setSelectedUser(user);
        form.setValues({
            username: user.username,
            email: user.email,
            role: user.role,
            password: '',
            status: user.status,
            avatar: user.avatar || ''
        });
        setAvatarFile(null);
        setAvatarPreview(user.avatar || null);
        setEditOpened(true);
    };

    // 打开删除确认
    const openDeleteConfirm = (user: User) => {
        setSelectedUser(user);
        setDeleteOpened(true);
    };

    // 处理头像上传
    const handleAvatarDrop = (files: FileWithPath[]) => {
        if (files.length > 0) {
            const file = files[0];
            setAvatarFile(file);
            const imageUrl = URL.createObjectURL(file);
            setAvatarPreview(imageUrl);
            // 在实际应用中，这里应该上传文件到服务器并获取URL
            // 这里我们模拟一个本地URL
            form.setFieldValue('avatar', imageUrl);
        }
    };

    // 独立上传头像
    const handleAvatarUpload = async () => {
        if (!avatarFile || !selectedUser) return;
        setAvatarUploading(true);
        try {
            const formData = new FormData();
            formData.append('avatar', avatarFile);
            const res = await axios.post(`/app-api/users/${selectedUser.id}/avatar`, formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            });
            if (res.data && res.data.avatar) {
                notifications.show({
                    title: '头像上传成功',
                    message: '用户头像已更新',
                    color: 'green',
                });
                setAvatarPreview(res.data.avatar);
                setAvatarFile(null);
                // 更新 selectedUser 的 avatar 字段
                setSelectedUser({ ...selectedUser, avatar: res.data.avatar });
                form.setFieldValue('avatar', res.data.avatar);
                fetchUsers();
            } else {
                notifications.show({
                    title: '头像上传失败',
                    message: res.data?.error || '请稍后再试',
                    color: 'red',
                });
            }
        } catch (error: any) {
            notifications.show({
                title: '头像上传失败',
                message: error?.response?.data?.error || error.message || '请稍后再试',
                color: 'red',
            });
        } finally {
            setAvatarUploading(false);
        }
    };

    // 提交编辑表单
    const handleEditSubmit = async (values: typeof form.values) => {
        try {
            if (selectedUser) {
                selectedUser.username = values.username;
                selectedUser.email = values.email;
                selectedUser.role = values.role;
                selectedUser.status = values.status;
                if (values.password) {
                    selectedUser.password = values.password;
                } else {
                    delete selectedUser.password;
                }
                await axios.put(`/app-api/users/${selectedUser.id}`, selectedUser, {
                    headers: { 'Content-Type': 'application/json' }
                });
                notifications.show({
                    title: '更新成功',
                    message: '用户信息已更新',
                    color: 'green',
                });
            } else {
                await axios.post('/app-api/register', values, {
                    headers: { 'Content-Type': 'application/json' }
                });
                notifications.show({
                    title: '创建成功',
                    message: '新用户已创建',
                    color: 'green',
                });
            }
            setEditOpened(false);
            if (avatarPreview) {
                URL.revokeObjectURL(avatarPreview);
                setAvatarPreview(null);
            }
            setAvatarFile(null);
            fetchUsers();
        } catch (error) {
            notifications.show({
                title: '操作失败',
                message: error instanceof Error ? error.message : '请稍后再试',
                color: 'red',
            });
        }
    };

    // 删除用户
    const handleDeleteUser = async () => {
        try {
            if (selectedUser) {
                await axios.delete(`/app-api/users/${selectedUser.id}`, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                notifications.show({
                    title: '删除成功',
                    message: '用户已删除',
                    color: 'green',
                });
                setDeleteOpened(false);
                // 刷新用户列表
                fetchUsers();
            }
        } catch (error) {
            notifications.show({
                title: '删除失败',
                message: error instanceof Error ? error.message : '请稍后再试',
                color: 'red',
            });
        }
    };

    // 获取角色标签颜色
    const getRoleBadgeColor = (role: string) => {
        switch (role) {
            case 'admin': return 'red';
            case 'expert': return 'blue';
            default: return 'green';
        }
    };

    // 获取状态标签颜色
    const getStatusBadgeColor = (status: string) => {
        return status === 'active' ? 'green' : 'gray';
    };

    // 表格行
    const rows = users.map((user) => (
        <Table.Tr key={user.id}>
            <Table.Td>{user.id}</Table.Td>
            <Table.Td>{user.username}</Table.Td>
            <Table.Td>{user.email}</Table.Td>
            <Table.Td>
                <Badge color={getRoleBadgeColor(user.role)}>
                    {user.role === 'admin' ? '管理员' : user.role === 'expert' ? '专家' : '普通用户'}
                </Badge>
            </Table.Td>
            <Table.Td>
                <Badge color={getStatusBadgeColor(user.status)}>
                    {user.status === 'active' ? '活跃' : '未激活'}
                </Badge>
            </Table.Td>
            <Table.Td>{formatDate(user.createdAt)}</Table.Td>
            <Table.Td>
                <Group gap="xs">
                    <ActionIcon variant="subtle" color="blue" onClick={() => openUserDetails(user)}>
                        <IconEye size={16} />
                    </ActionIcon>
                    <ActionIcon variant="subtle" color="green" onClick={() => openEditUser(user)}>
                        <IconEdit size={16} />
                    </ActionIcon>
                    <ActionIcon variant="subtle" color="red" onClick={() => openDeleteConfirm(user)}>
                        <IconTrash size={16} />
                    </ActionIcon>
                </Group>
            </Table.Td>
        </Table.Tr>
    ));

    return (
        <Stack gap="lg" p="md">
            <Card withBorder shadow="sm" padding="md">
                <Group justify="space-between" mb="md">
                    <Group>
                        <IconUserCircle size={24} style={{ color: 'var(--mantine-color-blue-6)' }} />
                        <Text fw={500} size="lg">用户管理</Text>
                    </Group>
                    <Button
                        leftSection={<IconPlus size={16} />}
                        onClick={() => {
                            form.reset();
                            setEditOpened(false);
                            setDetailsOpened(false);
                            setDeleteOpened(false);
                            setSelectedUser(null);
                            form.setValues({
                                username: '',
                                email: '',
                                role: 'user',
                                password: '',
                                status: 'active'
                            });
                            setEditOpened(true);
                        }}
                    >
                        新建用户
                    </Button>
                </Group>

                <Group mb="md">
                    <TextInput
                        placeholder="搜索用户名、邮箱或角色"
                        value={searchTerm}
                        onChange={(event) => setSearchTerm(event.currentTarget.value)}
                        style={{ flex: 1 }}
                        leftSection={<IconSearch size={16} />}
                    />
                </Group>

                <ScrollArea>
                    <Table striped highlightOnHover withTableBorder>
                        <Table.Thead>
                            <Table.Tr>
                                <Table.Th>ID</Table.Th>
                                <Table.Th>用户名</Table.Th>
                                <Table.Th>邮箱</Table.Th>
                                <Table.Th>角色</Table.Th>
                                <Table.Th>状态</Table.Th>
                                <Table.Th>创建时间</Table.Th>
                                <Table.Th>操作</Table.Th>
                            </Table.Tr>
                        </Table.Thead>
                        <Table.Tbody>
                            {loading ? (
                                <Table.Tr>
                                    <Table.Td colSpan={7}>
                                        <Group justify="center" py="md">
                                            <Loader size="sm" />
                                            <Text>加载中...</Text>
                                        </Group>
                                    </Table.Td>
                                </Table.Tr>
                            ) : rows.length === 0 ? (
                                <Table.Tr>
                                    <Table.Td colSpan={7}>
                                        <Text ta="center" py="md">没有找到匹配的用户</Text>
                                    </Table.Td>
                                </Table.Tr>
                            ) : rows}
                        </Table.Tbody>
                    </Table>
                </ScrollArea>

                <Group justify="center" mt="md">
                    <Pagination
                        total={totalPages}
                        value={activePage}
                        onChange={(page) => {
                            setActivePage(page);
                            fetchUsers(page);
                        }}
                    />
                </Group>
            </Card>

            {/* 用户详情模态框 */}
            <Modal
                opened={detailsOpened}
                onClose={() => setDetailsOpened(false)}
                title={(
                    <Group gap="xs">
                        <IconUserCircle size={24} style={{ color: 'var(--mantine-color-blue-6)' }} />
                        <Text size="lg" fw={600}>用户详情</Text>
                    </Group>
                )}
                size="lg"
                centered
            >
                {selectedUser && (
                    <Stack gap="lg">
                        <Center mb="md">
                            <Avatar
                                src={selectedUser.avatar}
                                alt={selectedUser.username}
                                size={120}
                                radius="xl"
                            />
                        </Center>
                        <Table withColumnBorders>
                            <Table.Tbody>
                                <Table.Tr>
                                    <Table.Td style={{ width: '150px' }}>
                                        <Group gap="xs">
                                            <Text fw={500} c="gray.6">用户ID</Text>
                                        </Group>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{selectedUser.id}</Text>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Group gap="xs">
                                            <Text fw={500} c="gray.6">用户名</Text>
                                        </Group>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{selectedUser.username}</Text>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Group gap="xs">
                                            <Text fw={500} c="gray.6">邮箱</Text>
                                        </Group>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{selectedUser.email}</Text>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Group gap="xs">
                                            <Text fw={500} c="gray.6">角色</Text>
                                        </Group>
                                    </Table.Td>
                                    <Table.Td>
                                        <Badge
                                            size="lg"
                                            variant="light"
                                            color={getRoleBadgeColor(selectedUser.role)}
                                            style={{ padding: '0.5rem 1rem' }}
                                        >
                                            {selectedUser.role === 'admin' ? '管理员' : selectedUser.role === 'expert' ? '专家' : '普通用户'}
                                        </Badge>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Group gap="xs">
                                            <Text fw={500} c="gray.6">状态</Text>
                                        </Group>
                                    </Table.Td>
                                    <Table.Td>
                                        <Badge
                                            size="lg"
                                            variant="light"
                                            color={getStatusBadgeColor(selectedUser.status)}
                                            style={{ padding: '0.5rem 1rem' }}
                                        >
                                            {selectedUser.status === 'active' ? '活跃' : '未激活'}
                                        </Badge>
                                    </Table.Td>
                                </Table.Tr>
                                <Table.Tr>
                                    <Table.Td>
                                        <Group gap="xs">
                                            <Text fw={500} c="gray.6">创建时间</Text>
                                        </Group>
                                    </Table.Td>
                                    <Table.Td>
                                        <Text size="lg">{formatDate(selectedUser.createdAt)}</Text>
                                    </Table.Td>
                                </Table.Tr>
                            </Table.Tbody>
                        </Table>
                    </Stack>
                )}
            </Modal>

            {/* 编辑用户模态框 */}
            <Modal
                opened={editOpened}
                onClose={() => setEditOpened(false)}
                title={selectedUser ? "编辑用户" : "新建用户"}
                centered
                size="lg"
            >
                <form onSubmit={form.onSubmit(handleEditSubmit)}>
                    <Stack gap="md">
                        {/* 头像上传区域 */}
                        {
                            selectedUser && (
                                <Stack gap="xs">
                                    <Text fw={500} size="sm">用户头像</Text>
                                    <Group justify="center" mb="md">
                                        {avatarPreview ? (
                                            <div style={{ position: 'relative' }}>
                                                <Avatar
                                                    src={avatarPreview}
                                                    alt="用户头像"
                                                    size={120}
                                                    radius="xl"
                                                />
                                                <ActionIcon
                                                    color="red"
                                                    variant="filled"
                                                    radius="xl"
                                                    size="sm"
                                                    style={{
                                                        position: 'absolute',
                                                        top: 0,
                                                        right: 0,
                                                    }}
                                                    onClick={() => {
                                                        if (avatarPreview) {
                                                            URL.revokeObjectURL(avatarPreview);
                                                        }
                                                        setAvatarPreview(null);
                                                        setAvatarFile(null);
                                                        form.setFieldValue('avatar', '');
                                                    }}
                                                >
                                                    <IconX size={14} />
                                                </ActionIcon>
                                            </div>
                                        ) : (
                                            <Avatar
                                                src={selectedUser?.avatar || null}
                                                alt="用户头像"
                                                size={120}
                                                radius="xl"
                                            />
                                        )}
                                    </Group>
                                    <Dropzone
                                        onDrop={handleAvatarDrop}
                                        accept={['image/png', 'image/jpeg', 'image/gif', 'image/svg+xml']}
                                        maxSize={3 * 1024 * 1024}
                                        multiple={false}
                                        p="md"
                                    >
                                        <Group justify="center" gap="xl" style={{ minHeight: 80, pointerEvents: 'none' }}>
                                            <Dropzone.Accept>
                                                <IconUpload size={32} stroke={1.5} color="var(--mantine-color-blue-6)" />
                                            </Dropzone.Accept>
                                            <Dropzone.Reject>
                                                <IconX size={32} stroke={1.5} color="var(--mantine-color-red-6)" />
                                            </Dropzone.Reject>
                                            <Dropzone.Idle>
                                                <IconPhoto size={32} stroke={1.5} />
                                            </Dropzone.Idle>
                                            <Stack gap={0} style={{ textAlign: 'center' }}>
                                                <Text size="sm" fw={700} inline>
                                                    拖放图片到此处或点击上传
                                                </Text>
                                                <Text size="xs" c="dimmed" inline>
                                                    支持PNG, JPG, GIF, SVG格式，文件大小不超过3MB
                                                </Text>
                                            </Stack>
                                        </Group>
                                    </Dropzone>
                                    {/* 独立上传头像按钮 */}
                                    <Button
                                        mt="xs"
                                        variant="outline"
                                        color="blue"
                                        loading={avatarUploading}
                                        disabled={!avatarFile || !selectedUser}
                                        onClick={handleAvatarUpload}
                                    >
                                        上传头像
                                    </Button>
                                </Stack>
                            )
                        }

                        <TextInput
                            label="用户名"
                            placeholder="输入用户名"
                            {...form.getInputProps('username')}
                        />
                        <TextInput
                            label="邮箱"
                            placeholder="输入邮箱"
                            {...form.getInputProps('email')}
                        />
                        <Select
                            label="角色"
                            placeholder="选择角色"
                            data={[
                                { value: 'admin', label: '管理员' },
                                { value: 'expert', label: '专家' },
                                { value: 'user', label: '普通用户' },
                            ]}
                            {...form.getInputProps('role')}
                        />
                        <Select
                            label="状态"
                            placeholder="选择状态"
                            data={[
                                { value: 'active', label: '活跃' },
                                { value: 'inactive', label: '未激活' },
                            ]}
                            {...form.getInputProps('status')}
                        />
                        <PasswordInput
                            label="密码"
                            placeholder="留空表示不修改密码"
                            {...form.getInputProps('password')}
                        />
                        <Group justify="flex-end" mt="md">
                            <Button variant="light" onClick={() => setEditOpened(false)}>取消</Button>
                            <Button type="submit">保存</Button>
                        </Group>
                    </Stack>
                </form>
            </Modal>

            {/* 删除确认模态框 */}
            <Modal
                opened={deleteOpened}
                onClose={() => setDeleteOpened(false)}
                title="确认删除用户"
                centered
            >
                {selectedUser && (
                    <Stack gap="md">
                        <Text>确定要删除用户 {selectedUser.username} 吗？此操作不可撤销。</Text>
                        <Group justify="flex-end">
                            <Button variant="default" onClick={() => setDeleteOpened(false)}>取消</Button>
                            <Button color="red" onClick={handleDeleteUser}>确认删除</Button>
                        </Group>
                    </Stack>
                )}
            </Modal>
        </Stack>
    );
}

export default Users;